package com.hengpeng.itfin.service.impl;

import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.exception.ServiceResultFactory;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.util.SignatureHelper;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.common.util.Validate;
import com.hengpeng.itfin.common.MessageUtil;
import com.hengpeng.itfin.common.SystemConfigUtil;
import com.hengpeng.itfin.constants.MSConstants;
import com.hengpeng.itfin.constants.SystemConfigConstants;
import com.hengpeng.itfin.service.UserInfoService;
import com.hengpeng.itfin.tools.Tools;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.en.AccountType;
import com.hengpeng.itfinbase.en.AuditStat;
import com.hengpeng.itfinbase.en.SubAccountType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.CorpOpenResponseMsg;
import com.hengpeng.itfinbase.message.partner.CorpRegisterQueryResponse;
import com.hengpeng.itfinbase.message.partner.OpenResponseMsg;
import com.hengpeng.itfinbase.message.userInfo.MobileBingRequest;
import com.hengpeng.itfinbase.message.userInfo.RealNameAuthRequest;
import com.hengpeng.itfinbase.message.userInfo.SendSMSRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoRegisterRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoResponse;
import com.hengpeng.itfinbase.message.userInfo.UserLoginRequest;
import com.hengpeng.itfinbase.message.userInfo.UserSetProtectPwdRequest;
import com.hengpeng.itfinbase.message.userInfo.UserUpdatePwdRequest;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.UserBankCard;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoStatus;
import com.hengpeng.itfinbase.persist.UserInfoLog;
import com.hengpeng.itfinbase.persist.UserInfoLog.MemberActionType;
import com.hengpeng.itfinbase.persist.VerifyCode.VerifyType;

@Service
@Lazy
@Transactional
public class UserInfoServiceImpl extends BaseServiceImpl implements UserInfoService
{
	@Override
	public UserInfoResponse register(UserInfoRegisterRequest request) {
		if (StringUtils.isEmpty(request.getUsername()) || StringUtils.isEmpty(request.getMobile()) || StringUtils.isEmpty(request.getPassword())) {
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class, RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
		}
		// 参数空值效验
		UserInfo user = serviceFactory.getDaoFactory().getUserInfoDao().getUserByUserName(request.getUsername());
		if (user != null) {
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class, RespCodeConstants.MemberCode.USERNAME_HAD_EXIST, "用户名已经存在");
		}
		logger.info("用户{" + request.getUsername() + "}进入注册流程...");

		user = serviceFactory.getDaoFactory().getUserInfoDao().getUserByMobile(request.getMobile());
		if (user != null) {
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class, RespCodeConstants.MemberCode.MOBILE_HAD_EXIST, "手机号码已经存在");
		}

		// 手机验证码验证
		SendSMSRequest smsrequest = new SendSMSRequest();
		smsrequest.setMobile(request.getMobile());
		smsrequest.setType(VerifyType.REGISTER);
		smsrequest.setVerifyCode(request.getVerifyCode());
		ResponseMessage msmres = serviceFactory.getSmsService().confirmValidSMS(smsrequest);
		if (!msmres.getRespCode().equals(RespCodeConstants.CommonCode.TRANS_SUC))
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class, msmres.getRespCode(),
					msmres.getRespDesc());
		}

		UserInfoResponse response = new UserInfoResponse();
		UserInfo userInfo = new UserInfo();
		userInfo.setUserLevel(UserInfo.UserLevel.LEVEL_ONE);
		userInfo.setUserName(request.getUsername().trim());
		userInfo.setPwdAttach(SystemConfigUtil.getConfigValue(SystemConfigConstants.LOGIN_PASSWORD_ATTACH));
		if (!Tools.validateObjectsNullOrEmpty(request.getPassword().trim())) {// 非空
			userInfo.setPassword(SignatureHelper.generateMD5Signture(request.getPassword().trim() + userInfo.getPwdAttach(),"utf-8"));
		}
		userInfo.setMobile(request.getMobile().trim());
		userInfo.setEmail(request.getEmail()==null?"":request.getEmail().trim());
		userInfo.setIsMobileCheck(BoolValue.YES);
		userInfo.setType(request.getType());
		userInfo.setRealName(request.getRealName());
		userInfo.setShortName(request.getShortName());
		userInfo.setOrganizeCode(request.getOrganizeCode());
		userInfo.setTaxCode(request.getTaxCode());
		userInfo.setBankPermitCode(request.getBankPermitCode());
		userInfo.setIsEmailCheck(BoolValue.NO);
		userInfo.setIsRealNameCheck(BoolValue.NO);
		userInfo.setRegisterFrom(request.getRegisterSource());
		userInfo.setRegisterTime(new Date());
		userInfo.setStatus(UserInfoStatus.NORMAL);
		userInfo.setIsInvestor(BoolValue.YES);
		userInfo.setIsBorrower(BoolValue.NO);
		userInfo.setLastLoginTime(new Date());
		userInfo.setUpdateTime(new Date());
		userInfo.setLoginFailNum(0);
		userInfo.setLoginSucNum(0);
		userInfo.setRecommendCode(request.getRecommendCode());
		userInfo.setRegisterFrom(request.getRegisterSource());
//		userInfo.setTrustAccountId("N" + ID.getInstanse().getID(18).toString());
		userInfo.setIsOpenAccount(BoolValue.NO);
		serviceFactory.getDaoFactory().getUserInfoDao().save(userInfo);
		Account account = new Account();
		account.setAccountType(AccountType.PERSONAL);
		account.setSubAccountType(SubAccountType.MERDT);
		account.setSubAccountId("MDT000001");
		account.setUserName(userInfo.getUserName().trim());
		account.setAccountName(account.getSubAccountType().getText());
		account.setUserId(userInfo.getId());
		account.setBaseMoney(0l);
		account.setBaseMoneyCollect(0l);
		account.setBaseMoneyRepay(0l);
		account.setCreateTime(new Date());
		account.setUpdateTime(new Date());
		account.setFreezeMoney(0l);
		account.setInComeMoneyCollect(0l);
		account.setInterestMoneyRepay(0l);
		account.setTotaldrawMoney(0l);
		account.setTotalfillMoney(0l);
		account.setTotalIncomeMoney(0l);
		account.setTotalInvestMoney(0l);
		account.setTotalInvestNum(0l);
		account.setTrustAccountId(userInfo.getTrustAccountId());
		serviceFactory.getPersistService().save(account);
		account.setUserName(userInfo.getUserName());
		response.setUserInfo(userInfo);
		response.setAccount(account);
		return response;
	}
    
	@Override
	public ServiceResult<UserInfo> dealOpenResult(OpenResponseMsg msg) {
		UserInfo member = serviceFactory.getDaoFactory().getUserInfoDao().get(Long.parseLong(msg.getMerPriv()));
		if (member != null) {
			String cardNumber = StringHelper.isEmpty(msg.getIdNo()) ? member.getCardNumber() : msg.getIdNo();
			String trustAccountId = msg.getUsrCustId(); 
			String mobile = StringHelper.isEmpty(msg.getUsrMp()) ? member.getMobile() : msg.getUsrMp();
			String email = StringHelper.isEmpty(msg.getUsrEmail()) ? member.getEmail() : msg.getUsrEmail(); 
			String realName = StringHelper.isEmpty(msg.getUsrName()) ? member.getRealName() : msg.getUsrName(); 
			
			int i = serviceFactory.getDaoFactory().getUserInfoDao().updateUserInfo(cardNumber, trustAccountId, mobile, email, realName, 
					BoolValue.YES, member.getId(), BoolValue.NO);
			if (i > 0) {
				Account account = serviceFactory.getAccountService().getAccount(member.getId());
				account.setTrustAccountId(msg.getUsrCustId());
				serviceFactory.getPersistService().update(account);
			}
			return ServiceResultFactory.getServiceResult(RespCodeConstants.CommonCode.TRANS_SUC, member);
		} else {
			return ServiceResultFactory.getServiceResult(RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND, UserInfo.class);
		}
	}

	@Override
	public ServiceResult<UserInfo> dealCorpOpenResult(CorpOpenResponseMsg msg) {
		try {
			UserInfo user = serviceFactory.getDaoFactory().getUserInfoDao().get(Long.parseLong(msg.getMerPriv()));
			if (user != null) {
				Account account = serviceFactory.getAccountService().getAccount(user.getId());
				if (account != null) {
					if (msg.getAuditDesc() != null) {
						user.setAuditDesc(URLDecoder.decode(msg.getAuditDesc(), MSConstants.UTF8));
					}
					user.setTrustAccountId(msg.getUsrCustId());
					user.setOpenBankId(msg.getOpenBankId());
					user.setCardId(msg.getCardId());
					serviceFactory.getDaoFactory().getUserInfoDao().update(user);
					account.setTrustAccountId(msg.getUsrCustId());
					serviceFactory.getPersistService().update(account);

					return ServiceResultFactory.getServiceResult(RespCodeConstants.CommonCode.TRANS_SUC, user);
				} else {
					return ServiceResultFactory.getServiceResult(RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND,
							UserInfo.class);
				}
			} else {
				return ServiceResultFactory.getServiceResult(RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND,
						UserInfo.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ServiceResultFactory.getServiceResult(RespCodeConstants.CommonCode.TRANS_FAIL_MSG, UserInfo.class);
	}

	@Override
	public UserInfoResponse login(UserLoginRequest request) {
		UserInfoResponse response = new UserInfoResponse();
		UserInfo user =  serviceFactory.getDaoFactory().getUserInfoDao().getUserByUserNameEmailMobile(request.getUsername());
		if (user == null) {
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class, RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND, "用户不存在");
		}
//		else if (user.getIsEmailCheck() == BoolValue.NO || user.getIsEmailCheck() == null) {
//			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class, RespCodeConstants.MemberCode.MEMBER_REALNAME_NOT_ACTIVE, "用户尚未激活");
//		} 
		else {
			if (SignatureHelper.generateMD5Signture(request.getPassword() + user.getPwdAttach(), "utf-8").equalsIgnoreCase(user.getPassword())) {
				response.setUserInfo(user);
				Account account = serviceFactory.getAccountService().getAccount(user.getId());
				response.setAccount(account);
			} else {
				return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,RespCodeConstants.MemberCode.ACCOUNT_INPUTPASSWD_ERROR, " 密码输入不正确");
			}
		}
		user.setLoginSucNum(user.getLoginSucNum() + 1);
		user.setLastLoginTime(new Date());
		serviceFactory.getPersistService().update(user);
		user.setLastLoginTime(new Date());
		UserInfoLog(user, MemberActionType.LOGIN);
		// 发送站内信
		serviceFactory.getMessageService().sendMessge(user);
		return response;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void UserInfoLog(UserInfo user, MemberActionType actionType)
	{
		UserInfoLog log = new UserInfoLog();
		log.setEntityId(user.getId().toString());
		log.setEntityName(UserInfo.class.getSimpleName());
		log.setIp(user.getLastLoginIp());
		log.setMemberActionType(actionType);
		log.setOperateTime(user.getLastLoginTime());
		log.setUserId(user.getUserName());
		log.setDescription(actionType.getText());
		serviceFactory.getPersistService().save(log);
	}

	@Override
	public UserInfo getUserByUserName(String userName)
	{
		return daoFactory.getUserInfoDao().getUserByUserName(userName);
	}

	@Override
	public ServiceResult<UserInfo> dealCorpRegisterQueryResult(CorpRegisterQueryResponse msg)
	{
		UserInfo user = getUserByBusiCode(msg.getBusiCode());
		if (user != null)
		{
			user.setAuditDesc(AuditStat.valueOf(msg.getAuditStat()).getText());
			if (msg.getUsrCustId() != null && !msg.getUsrCustId().trim().equals(""))
			{
				user.setTrustAccountId(msg.getUsrCustId());
			}
			daoFactory.getUserInfoDao().save(user);
		}
		return ServiceResultFactory.getServiceResult(RespCodeConstants.CommonCode.TRANS_SUC, user);
	}

	@Override
	public UserInfo getUserByTrustAccountId(String trustAccountId)
	{
		return daoFactory.getUserInfoDao().getUserByTrustAccountId(trustAccountId);
	}

	@Override
	public UserInfo getUserByBusiCode(String busiCode)
	{
		return daoFactory.getUserInfoDao().getUserByBusiCode(busiCode);
	}

	/**
	 * 实名认证
	 * @param request
	 */
	public UserInfoResponse realNameAuth(RealNameAuthRequest request)
	{
		UserInfoResponse response = new UserInfoResponse();
		if (request.getRealName() == null || request.getRealName().length() == 0 || request.getCardNumber() == null
				|| request.getCardNumber().length() == 0)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
		}
		UserInfo user = getUserByUserName(request.getUserName());
		if (user != null)
		{
			user.setUpdateTime(new Date());
			user.setRealName(request.getRealName());
			user.setCardNumber(request.getCardNumber());
			user.setIsRealNameCheck(BoolValue.YES);
			daoFactory.getUserInfoDao().update(user);
			response.setUserInfo(user);
			return response;
		}
		else
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND, "用户不存在");
		}
	}

	/**
	 * 修改密码
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public UserInfoResponse updatePassword(UserUpdatePwdRequest request)
	{
		UserInfoResponse response = new UserInfoResponse();
		UserInfo user = getUserByUserName(request.getUserName());
		if (request.getPassword() == null || request.getPassword().length() == 0)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
		}
		if (user != null)
		{
			if (!StringHelper.isEmpty(request.getOldPassword()))
			{
				if (!SignatureHelper.generateMD5Signture(request.getOldPassword() + user.getPwdAttach(), "utf-8")
						.equalsIgnoreCase(user.getPassword()))
				{
					return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
							RespCodeConstants.MemberCode.ACCOUNT_INPUTPASSWD_ERROR, "老密码错误");
				}
			}
			user.setUpdateTime(new Date());
			user.setPassword(SignatureHelper.generateMD5Signture(request.getPassword() + user.getPwdAttach(), "utf-8"));
			daoFactory.getUserInfoDao().update(user);
			return response;
		}
		else
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND, "用户不存在");
		}
	}

	/**
	 * 设置密保
	 */
	public UserInfoResponse doSetQuestionPwd(UserSetProtectPwdRequest request)
	{
		UserInfoResponse response = new UserInfoResponse();
		UserInfo user = getUserByUserName(request.getUserName());
		if (request.getQuestionType() == null || StringUtils.isEmpty(request.getAnswer()))
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
		}
		if (user != null)
		{
			user.setQuestionType(request.getQuestionType());
			user.setAnswer(request.getAnswer());
			user.setIsQuestionCheck(BoolValue.YES);
			daoFactory.getUserInfoDao().update(user);
			response.setUserInfo(user);
			return response;
		}
		else
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND, "用户不存在");
		}
	}

	/**
	 * <pre>
	 * 添加账户银行卡
	 * </pre>
	 * @param UserBankCard {userName:用户名, providerId:服务商, realName:真实姓名, accountNo:绑定账号, bankName:银行名称, province:银行省份,
	 *        city:银行城市, branch:分行名称, subbranch:支行名称 }
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseMessage saveUserBankCard(UserBankCard bindAccount)
	{
		if (Validate.validateObjectsNullOrEmpty(bindAccount.getBankCardNo(), bindAccount.getBankName(),
				bindAccount.getUserName(), bindAccount.getRealName(), bindAccount.getProvince(), bindAccount.getCity(),
				bindAccount.getSubbranch(), bindAccount.getIsPriority()))
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
		}
		UserInfo user = getUserByUserName(bindAccount.getUserName());
		if (user == null)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND, "用户不存在");
		}
		if (user.getIsRealNameCheck() != BoolValue.YES)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.MemberCode.MEMBER_REALNAME_CHECK_NO, "请先实名认证");
		}
		List<UserBankCard> list = serviceFactory.getDaoFactory().getUserBankCardDao()
				.findUserBankCardByNO(bindAccount.getUserName(), bindAccount.getBankCardNo());
		if (list != null && list.size() > 0)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "银行卡已经存在");
		}
		if (bindAccount.getIsPriority() == BoolValue.YES)
		{
			DynamicQuery query = new DynamicQuery(UserBankCard.class);
			query.eq("userName", bindAccount.getUserName());
			query.eq("isPriority", BoolValue.YES);
			List<UserBankCard> bindList = serviceFactory.getDaoFactory().getCommonDao()
					.findEntityByDynamicQuery(query, UserBankCard.class);
			for (UserBankCard bat : bindList)
			{
				bat.setIsPriority(BoolValue.NO);
			}
			serviceFactory.getDaoFactory().getCommonDao().updateAllEntity(bindList);
		}
		serviceFactory.getDaoFactory().getCommonDao().saveEntity(bindAccount);
		return new ResponseMessage();
	}

	/**
	 * <pre>
	 *  绑定银行卡
	 * </pre>
	 * @param UserBankCard
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseMessage userBindCard(UserBankCard bindAccount)
	{
		if (Validate.validateObjectsNullOrEmpty(bindAccount.getId()))
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
		}
		UserInfo user = getUserByUserName(bindAccount.getUserName());
		if (user == null)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND, "用户不存在");
		}

		bindAccount = serviceFactory.getDaoFactory().getCommonDao().getEntity(UserBankCard.class, bindAccount.getId());
		if (bindAccount == null)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "银行卡不存在");
		}
		DynamicQuery query = new DynamicQuery(UserBankCard.class);
		query.eq("userName", bindAccount.getUserName());
		query.eq("isPriority", BoolValue.YES);
		List<UserBankCard> bindList = serviceFactory.getDaoFactory().getCommonDao()
				.findEntityByDynamicQuery(query, UserBankCard.class);
		for (UserBankCard bat : bindList)
		{
			bat.setIsPriority(BoolValue.NO);
		}
		serviceFactory.getDaoFactory().getCommonDao().updateAllEntity(bindList);
		bindAccount.setIsPriority(BoolValue.YES);
		serviceFactory.getDaoFactory().getCommonDao().updateEntity(bindAccount);
		return new ResponseMessage();
	}

	/**
	 * <pre>
	 * 修改绑定资金账户
	 * </pre>
	 * @param UserBankCard { providerId:服务商, accountNo:绑定账号, bankName:银行名称, province:银行省份, city:银行城市, branch:分行名称,
	 *        subbranch:支行名称 }
	 * @return 绑定资金账户
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseMessage updateUserBindCard(UserBankCard bindAccount)
	{
		if (Validate.validateObjectsNullOrEmpty(bindAccount.getId(), bindAccount.getBankCardNo(),
				bindAccount.getBankName(), bindAccount.getRealName(), bindAccount.getProvince(), bindAccount.getCity(),
				bindAccount.getSubbranch(), bindAccount.getIsPriority()))
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
		}
		UserInfo user = getUserByUserName(bindAccount.getUserName());
		if (user == null)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND, "用户不存在");
		}
		DynamicQuery queryBank = new DynamicQuery(UserBankCard.class);
		queryBank.eq("userName", bindAccount.getUserName());
		queryBank.eq("bankCardNo", bindAccount.getBankCardNo());
		queryBank.ne("id", bindAccount.getId());
		List<UserBankCard> list = serviceFactory.getDaoFactory().getCommonDao()
				.findEntityByDynamicQuery(queryBank, UserBankCard.class);
		if (list != null && list.size() > 0)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "银行卡已经存在");
		}
		if (bindAccount.getIsPriority() == BoolValue.YES)
		{
			DynamicQuery query = new DynamicQuery(UserBankCard.class);
			query.eq("userName", bindAccount.getUserName());
			query.eq("isPriority", BoolValue.YES);
			List<UserBankCard> bindList = serviceFactory.getDaoFactory().getCommonDao()
					.findEntityByDynamicQuery(query, UserBankCard.class);
			for (UserBankCard bat : bindList)
			{
				bat.setIsPriority(BoolValue.NO);
			}
			serviceFactory.getDaoFactory().getCommonDao().updateAllEntity(bindList);
		}
		serviceFactory.getDaoFactory().getCommonDao().updateEntity(bindAccount);
		return new ResponseMessage();
	}

	/**
	 * <pre>
	 *  删除绑定资金账户
	 * </pre>
	 * @param betCardNo 投注卡号
	 * @param id 绑定资金账户ID
	 * @return 成功信息
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseMessage removeUserBindCard(Long id)
	{
		UserBankCard bindAccount = serviceFactory.getDaoFactory().getCommonDao().getEntity(UserBankCard.class, id);
		if (bindAccount == null)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "银行卡不存在");
		}
		DynamicQuery query = new DynamicQuery(UserBankCard.class);
		query.eq("userName", bindAccount.getUserName());
		List<UserBankCard> bindList = serviceFactory.getDaoFactory().getCommonDao()
				.findEntityByDynamicQuery(query, UserBankCard.class);

		serviceFactory.getDaoFactory().getCommonDao().deleteEntity(UserBankCard.class, id);
		if (bindList.size() > 1)
		{
			UserBankCard bind = null;
			for (UserBankCard ba : bindList)
			{
				if (!ba.getId().equals(id))
				{
					bind = ba;
					break;
				}
			}
			if (bind != null)
			{
				serviceFactory.getUserInfoService().userBindCard(bind);
			}
		}
		return new ResponseMessage();
	}

	/**
	 * <pre>
	 * 绑定手机号码
	 * </pre>
	 * @param request
	 * @return
	 */
	public ResponseMessage bingMobile(MobileBingRequest request)
	{
		if (Validate.validateObjectsNullOrEmpty(request.getUserName()))
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
		}
		UserInfo user = getUserByUserName(request.getUserName());
		if (user == null)
		{
			return MessageUtil.getErrorResponseMessage(UserInfoResponse.class,
					RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND, "用户不存在");
		}
		// 检查用户状态是否正常
		if (user.getStatus() != UserInfoStatus.NORMAL)
		{
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,
					RespCodeConstants.MemberCode.MEMBER_STATUS_EXCEPTION, "用户状态不正确");
		}
		if (user.getIsMobileCheck() == BoolValue.YES && request.getMobile().equals(user.getMobile()))
		{
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL,
					"新手机号码和老手机号码重复");
		}
		DynamicQuery query = new DynamicQuery(UserInfo.class);
		query.eq("mobile", request.getMobile());
		List<UserInfo> list = serviceFactory.getPersistService().findByDynamicQuery(UserInfo.class, query);
		if (list != null && list.size() > 0)
		{
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL,
					"该手机号码已经存在");
		}
		// 修改用户手机为当前验证手机和手机是否验证标识
		user.setMobile(request.getMobile());
		user.setIsMobileCheck(BoolValue.YES);
		serviceFactory.getPersistService().update(user);
		return new ResponseMessage();
	}
}
